﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperJoe.Framework.Logging
{
    public static class LoggerUtil
    {
        static ILogger logger = new DefaultLogger();

        public static void Init(ILogger logger)
        {
            LoggerUtil.logger = logger;
        }

        public static void Info(string message, object data = null)
        {
            logger.Info(message, data);
        }

        public static void Warn(string message)
        {
            logger.Warn(message);
        }

        public static void Debug(string message)
        {
            logger.Debug(message);
        }

        public static void Error(string message = null, Exception ex = null, object data = null)
        {
            logger.Error(message, ex, data);
        }

        public static BlockInfo BlockInfo(string startMessage, string endMessage, bool logTimeCost = false)
        {
            return new BlockInfo(startMessage, endMessage, logTimeCost);
        }
    }

    public struct BlockInfo : IDisposable
    {
        private string endMessage;
        private Stopwatch stopwatch;

        internal BlockInfo(string startMessage, string endMessage, bool logTimeCost)
        {
            this.endMessage = endMessage;

            if (!string.IsNullOrWhiteSpace(startMessage))
            {
                LoggerUtil.Info(startMessage);
            }

            if (logTimeCost)
            {
                stopwatch = Stopwatch.StartNew();
                stopwatch.Start();
            }
            else
            {
                stopwatch = null;
            }
        }

        public void Dispose()
        {
            string message = null;

            if (stopwatch != null)
            {
                stopwatch.Stop();
                message = string.IsNullOrWhiteSpace(endMessage) ? ("[消耗时间：" + stopwatch.Elapsed + "]") : (endMessage + "[消耗时间：" + stopwatch.Elapsed + "]");
            }
            else
            {
                message = endMessage;
            }

            if (!string.IsNullOrWhiteSpace(message))
            {
                LoggerUtil.Info(message);
            }
        }
    }
}
